package com.cmc6.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.cmc6.common.constant.BaseConstant;
import com.cmc6.common.model.enums.SocketMessageEnum;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * Kafka 工具类
 */
@Component
public class KafkaUtil {

    private static KafkaTemplate<String, String> kafkaTemplate;

    @Resource
    private void setKafkaTemplate(KafkaTemplate<String, String> val) {
        KafkaUtil.kafkaTemplate = val;
    }

    /**
     * 给【socket】发送消息：通过 消息中间件
     * {@link com.cmc6.websocket.listener.SocketKafkaListener}
     */
    private static void sendSocketMsgByMq(SocketMessageEnum socketMessageEnum) {
        kafkaTemplate.send(BaseConstant.KAFKA_SOCKET_TOPIC, socketMessageEnum.toJsonString());
    }

    /**
     * 消息推送：公告推送
     */
    public static void bulletinPush(Set<Long> userIdSet) {

        SocketMessageEnum newNotify = SocketMessageEnum.NEW_BULLETIN;
        newNotify.setJson(JSONUtil.createObj().set("userIdSet", userIdSet));
        sendSocketMsgByMq(newNotify);

    }

    /**
     * 消息推送：有新的通知
     */
    public static void refreshNoReadNotifyCount(Set<Long> userIdSet) {

        if (CollUtil.isEmpty(userIdSet)) {
            return;
        }

        SocketMessageEnum newNotify = SocketMessageEnum.NEW_NOTIFY;
        newNotify.setJson(JSONUtil.createObj().set("userIdSet", userIdSet));
        sendSocketMsgByMq(newNotify);

    }

    /**
     * 消息推送：账号在其他地方登录，您被迫下线
     */
    public static void forcedOffline(Set<Long> socketIdSet, Set<Long> userIdSet) {

        if (CollUtil.isEmpty(socketIdSet) && CollUtil.isEmpty(userIdSet)) {
            return;
        }

        SocketMessageEnum forcedOffline = SocketMessageEnum.FORCED_OFFLINE;
        forcedOffline.setJson(JSONUtil.createObj().set("socketIdSet", socketIdSet).set("userIdSet", userIdSet));
        sendSocketMsgByMq(forcedOffline);

    }

    /**
     * 消息推送：登录过期，请重新登录
     */
    public static void loginExpired(Set<Long> socketIdSet) {

        if (CollUtil.isEmpty(socketIdSet)) {
            return;
        }

        SocketMessageEnum loginExpired = SocketMessageEnum.LOGIN_EXPIRED;
        loginExpired.setJson(JSONUtil.createObj().set("socketIdSet", socketIdSet));
        sendSocketMsgByMq(loginExpired);

    }

    /**
     * 消息推送：账号已被注销
     */
    public static void delAccount(Set<Long> userIdSet) {

        if (CollUtil.isEmpty(userIdSet)) {
            return;
        }

        SocketMessageEnum delAccount = SocketMessageEnum.DEL_ACCOUNT;
        delAccount.setJson(JSONUtil.createObj().set("userIdSet", userIdSet));
        sendSocketMsgByMq(delAccount);

    }

}
